<?php
/**
 * Soar Framework - Lightweight and simple to use PHP Framework
 *
 * Soar is free software and is distributed WITHOUT ANY WARRANTY
 *
 * @package Soar
 * @version 1.0 $Id: SoarErrorHandler.php 2 2012-04-06 21:50:33Z shay@shayanderson.com $
 * @copyright Copyright (c) 2012 ShayAnderson.com
 * @license http://www.gnu.org/licenses/gpl.html GPL License
 * @link http://www.shayanderson.com/projects/soar-php-framework.htm
 */

/**
 * Soar Framework Error Handler
 *
 * @package Soar
 * @name SoarErrorHandler
 * @author Shay Anderson 03.12
 */
class SoarErrorHandler
{
	/**
	 * Error types
	 */
	const ERROR = E_USER_ERROR;
	const NOTICE = E_USER_NOTICE;
	const WARNING = E_USER_WARNING;
	
	/**
	 * Format message for log
	 * 
	 * @param string $message
	 * @return string
	 */
	private function __formatLogMessage($message)
	{
		return strip_tags(preg_replace('/\<br ?\/?\>/i', PHP_EOL, $message));
	}
	
	/**
	 * Error handler
	 * 
	 * @param string $err_message
	 * @return void
	 */
	private static function __handleError($err_message)
	{
		if(SoarConf::getInstance()->core->debug)
		{
			echo $err_message;
			echo '<pre>' . print_r(debug_backtrace(), true) . '</pre>';
		}
		else
		{
			Soar::runError(Soar::ERROR_500);
		}
		Soar::log(self::__formatLogMessage($err_message), SoarDebugger::LEVEL_ERROR);
		Soar::finalize();
		exit;
	}
	
	/**
	 * Notice handler
	 * 
	 * @param string $notice_message
	 * @return void
	 */
	private static function __handleNotice($notice_message)
	{
		if(SoarConf::getInstance()->core->debug)
		{
			echo $notice_message;
			echo '<pre>' . print_r(debug_backtrace(), true) . '</pre>';
		}
		Soar::log(self::__formatLogMessage($notice_message), SoarDebugger::LEVEL_DEBUG);
	}

	/**
	 * Handle error
	 *
	 * @param int $err_num
	 * @param string $err_message
	 * @param string $err_file
	 * @param int $err_line
	 * @param array $err_vars
	 * @return bool
	 */
	public static function handle($err_num, $err_message, $err_file, $err_line, $err_vars)
	{
		if(!(error_reporting() & $err_num))
		{
			// invalid error code
			return true;
		}
		$err_str = "<br /><b>Application %1\$s:</b> [{$err_num}] {$err_message}<br />"
			. "%1\$s occurred in file {$err_file} (line {$err_line})<br />";
		switch($err_num)
		{
			// handle by error type
			case self::ERROR:
			case E_ERROR:
				self::__handleError(sprintf($err_str, 'Fatal Error')
					. 'PHP ' . PHP_VERSION . ' (' . PHP_OS . ')');
				exit;
				break;
			case self::WARNING:
			case E_WARNING:
				self::__handleError(sprintf($err_str, 'Warning'));
				break;
			case self::NOTICE:
			case E_NOTICE:
				self::__handleNotice(sprintf($err_str, 'Notice'));
				break;
			default:
				self::__handleNotice(sprintf($err_str, 'Unknown Error'));
				break;
		}

		// error handled
		return true;
	}
}
?>